import { PlusOutlined } from "@ant-design/icons";
import { Input, DatePicker, Button } from "antd";
import { useEffect, useState, useContext } from "react";
import "./index.css";
import Item from "@/components/item";
import { searchContext } from "@/store";
import axios from 'axios'


const Todo = (props) => {
  const [inputValue, setInputValue] = useState("");
  const [addTime, setAddTime] = useState("");
  const [items, setItems] = useState([]);

  const { searchValue } = useContext(searchContext);

  useEffect(() => {
    getListData()
  }, [])

  const getListData = () => {
    axios.post('/api/getList', {
      data: {}
    }).then((response) => {
      setItems([...response.data]);
    }).catch((error) => {
      console.log(error);
    });
  }

  const handleAdd = () => {
    let value = inputValue.trim();
    if (value === "") {
      return;
    }
    let todo = {};
    todo.id = new Date().getTime();
    todo.value = value;
    todo.hasCompleted = false;
    todo.deadline = addTime;
    setInputValue("");
    axios.post('/api/add', {
      data: todo
    }).then((response) => {
      getListData()
    }).catch((error) => {
      console.log(error);
    });
  };



  //点右边的关闭按钮，删除列表中的内容（删除数组todosData中的内容）
  const onDestroy = (todo) => {
    axios.post('/api/del', {
      data: todo.id
    }).then((response) => {
      getListData()
    }).catch((error) => {
      console.log(error);
    });
  };


  //列表的状态变化时，改变对应的hasCompleted
  const singleSelect = (todo) => {
    todo.hasCompleted = !todo.hasCompleted
    axios.post('/api/update', {
      data: todo
    }).then((response) => {
      getListData()
    }).catch((error) => {
      console.log(error);
    });
  };

  const itemEditDone = (todo, val, deadline) => {
    todo.value = val
    todo.deadline = deadline
    axios.post('/api/update', {
      data: todo
    }).then((response) => {
      getListData()
    }).catch((error) => {
      console.log(error);
    });
  };

  const onAddTimeChange = (date, dateString) => {
    setAddTime(dateString);
  };

  const filterItems = items.filter((item) => {
    if (props.filter === "done" && !item.hasCompleted) {
      return false
    }
    if (searchValue !== '' && item.value.indexOf(searchValue) == -1){
      return false
    }
    return true
  });

  return (
    <div>
      {searchValue !== "" ? (
        <></>
      ) : (
        <div className="wrap-search">
          <Input
            size="large"
            className="add-input"
            placeholder="添加任务"
            prefix={<PlusOutlined />}
            value={inputValue}
            onChange={(e) => {
              setInputValue(e.target.value);
            }}
          />
          <DatePicker onChange={onAddTimeChange}  style={{height: '38px'}}/>
          <Button onClick={handleAdd} style={{height: '38px', marginLeft: '10px'}} type="default">添加</Button>
        </div>
      )}
      <section className="main">
        <ul className="todo-list">
          {filterItems.map((elem, i) => {
            return (
              <Item
                {...{ onDestroy, todo: elem, singleSelect, itemEditDone }}
                key={i}
              />
            );
          })}
        </ul>
      </section>
    </div>
  );
};

export default Todo;
